import React, { Component } from "react";

import {langs} from './ui_lang';

import PageContent from '../PageContent'

import {Badge,Card,Modal} from 'antd';

import { ajax ,showResultMessage,getLocalMessage} from '../common';

import {UIDataTableView} from '../uicomponents/UIDataComponentView';
import UIForm from '../uicomponents/UIForm';
/**
 * 系统用户列表
 */

class SysAccountListPanel extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    /**
     * 系统用户列表事件处理
     */
    actionHandler = (actionEvent) => {
        const { accountListRef, selectSysAccountIds } = this;
        const result = {};
        return {
            deleteSysAccounts: (actionEvent) => {

                let selectIds = [];

                if (actionEvent.params != null) {
                    selectIds.push(actionEvent.params.id);
                }
                else {
                    selectIds = selectSysAccountIds;
                }

                ajax('SYSTEM/ACCOUNT/deleteSysAccount', { 'ids':selectIds } ).then((data) => {
                    if (data) {
                        accountListRef.loadData();
                        result.success = true;
                        result.message = 'message.deleteSuccess';
                    }
                }).catch((message) => {
                    result.success = false;
                    result.message = message;
                }).finally(() => {
                    showResultMessage(result);
                });
            },
            refresh: () => {
                accountListRef.loadData();
            }
        };
    }

    render() {

        return (
            <UIDataTableView {...this.props}
                title={getLocalMessage('sysAccountListPanel.listTitle')}
                tableConfigId="systemUserList"
                dataUrl="SYSTEM/ACCOUNT/querySysAccounts"
                actionGroupId="sysAccountListActionGroup"
                rowActionGroupId="sysAccountRowActionGroup"
                selectMode="multi"
                searchFormId="sysUserQueryForm"
                autoLoad={true}
                ref={(inst) => this.accountListRef = inst}
                actionHandler={this.actionHandler}
                cellRender={(column, CellContent, data, dataSet) => {
                    if (column.property === 'status') {
                        CellContent.splice(0, 0, <Badge key={data.id} status={data.status === 'FREE' ? 'processing' : 'error'} />);
                    }
                }}
                onSelectChange={
                    (selectRowKeys) => {
                        this.selectSysAccountIds = selectRowKeys;
                    }
                }
                setToolbarState={(topToolBar, selectRowKeys) => {
                    if (selectRowKeys.length > 0) {
                        topToolBar.enable('delete');
                        topToolBar.enable('edit');
                        topToolBar.enable('configSysAccountRole');
                        topToolBar.enable('setSysAccountPassword');
                    } else {
                        topToolBar.disable('delete');
                        topToolBar.disable('edit');
                        topToolBar.disable('configSysAccountRole');
                        topToolBar.disable('setSysAccountPassword');
                    }
                }}
            />
        );
    }
}

/**
 * 新增系统帐号
 */
class AddNewSysAccountPanel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    actionHandler = (actionEvent) => {
        const { component } = actionEvent;
        const owner = this;
        return {
            doSave: () => {
                component.getFormData((formData) => {
                    ajax('SYSTEM/ACCOUNT/saveSysAccount', formData).then((data) => {
                        if (data) {
                            Modal.confirm({
                                title: getLocalMessage('message.saveSuccess'),
                                iconType: 'check-circle',
                                cancelText: '返回系统帐列表',
                                okText: '继续新建系统帐号',
                                onOk() {
                                    component.resetForm();
                                },
                                onCancel() {
                                    owner.props.history.push('/');
                                },
                            });
                        }
                    }).catch((reason) => {
                        showResultMessage({ success: false, message: reason });
                    });
                });
            },

        };

    }

    render() {
        return (
            <Card>
                <UIForm {...this.props}
                    formConfigId="sysUserInfoForm"
                    actionGroupId="formAddNewEditorActionGroup"
                    actionHandler={this.actionHandler} />
            </Card>
        );
    }
}

/**
 * 编辑系统帐号
 */
class EditSysAccountPanel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    actionHandler = (actionEvent) => {
        const { component } = actionEvent;
        const result = {};
        return {
            doSave: () => {
                component.getFormData(function (formData) {
                    ajax('SYSTEM/ACCOUNT/saveSysAccount', formData).then(function (data) {
                        if (data) {
                            result.success = true;
                            result.message = 'message.saveSuccess';
                        }
                    }).catch(function (reason) {
                        result.success = false;
                        result.message = reason;
                    }).finally(() => {
                        showResultMessage(result);
                    });
                });
            },
        };
    }

    render() {
        return (
            <Card title={this.props.location.state.name} >
                <UIForm {...this.props}
                    disabledFileds={{ account: true }}
                    formConfigId="sysUserInfoForm"
                    actionGroupId="formAddNewEditorActionGroup"
                    actionHandler={this.actionHandler} />
            </Card>
        );
    }
}

/** 
 * 选择系统角色
*/
class ChooseSysRoleListModalPanel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    render() {

        return (
            <UIDataTableView {...this.props}
                ref={(inst) => this.chooseSysRoleListRef = inst}
                title={getLocalMessage('sysAccountListPanel.chooseAccountRole')}
                width={800}
                actionGroupId="chooseRelatedItemListActionGroup"
                tableConfigId="sysRoleTable"
                dataUrl="SYSTEM/SYSROLE/querySysAccountNoRoleList"
                selectMode="multi"
                inPop={true}
                autoLoad={false}
                destroyOnClose={true}
                onSelectChange={(selectRowKeys) => {
                    this.props.onSelectSysRole(selectRowKeys);
                }}
                setToolbarState={(topToolBar, selectSysRoleIds) => {
                    if (selectSysRoleIds.length > 0) {
                        topToolBar.enable('ok');
                    } else {
                        topToolBar.disable('ok');
                    }
                }
                }
            />

        );
    }
}

/** 
 * 选择系统角色组
*/
class ChooseSysRoleGroupListModalPanel extends React.Component {

    render() {

        return (
            <UIDataTableView {...this.props}
                ref={(inst) => this.chooseSysRoleGroupListRef = inst}
                width={800}
                title={getLocalMessage('sysAccountListPanel.chooseAccountRoleGroup')}
                actionGroupId="chooseRelatedItemListActionGroup"
                tableConfigId="sysRoleGroupListTable"
                dataUrl="SYSTEM/SYSROLE/querySysAccountNoRoleGroupList"
                selectMode="multi"
                inPop={true}
                autoLoad={false}
                destroyOnClose={true}
                onSelectChange={(selectRowKeys) => {
                    this.props.onSelectSysRole(selectRowKeys);
                }}
                setToolbarState={(topToolBar, selectSysRoleIds) => {
                    if (selectSysRoleIds.length > 0) {
                        topToolBar.enable('ok');
                    } else {
                        topToolBar.disable('ok');
                    }
                }}
            />

        );

    }
}

/** 
 * 设置系统帐号角色
*/
class ConfigSysAccountRolesPanel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    actionHandler = (actionEvent) => {
        const { sysAccount, chooseSysRoleListModalRef, chooseSysRoleGroupListModalRef } = this;

        return {
            addSysAccountRoleRelation: () => {
                chooseSysRoleListModalRef.openModal(() => {
                    chooseSysRoleListModalRef.loadData({ accountId: sysAccount.id });
                });
            },
            addSysAccountRoleGroupRelation: () => {
                chooseSysRoleGroupListModalRef.openModal(() => {
                    chooseSysRoleGroupListModalRef.loadData({ accountId: sysAccount.id });
                });
            },
            doRemove: () => {
                const { accountRoleListRef, selectSysAccountRoleIds } = this;
                const result = {};
                ajax('SYSTEM/ACCOUNT/removeSysAccountRoles', { sysAccountId: sysAccount.id, sysAccountRoleIds: selectSysAccountRoleIds.join(',') })
                    .then((data) => {
                        result.success = true;
                        result.message = 'message.deleteSuccess';
                        accountRoleListRef.loadData({ sysAccountId: sysAccount.id });
                    }).catch((message) => {
                        result.success = false;
                        result.message = message;
                    }).finally(() => {
                        showResultMessage(result);
                    });
            }

        };
    }

    chooseRoleActionHandler = (actionEvent) => {
        
        const { accountRoleListRef, sysAccount, selectSysRoleIds } = this;
        const { component } = actionEvent;
        return {
            cancelChoose: () => {
                component.closeModal();
            },
            addRelatedItems: () => {
                const result = {};
                ajax('SYSTEM/ACCOUNT/addSysAccountRoles', {
                    sysAccountId: sysAccount.id,
                    sysRoleIds: selectSysRoleIds.join(',')
                }).then(() => {
                    result.success = true;
                    result.message = 'message.addAccountRoleSuccess';
                    component.closeModal();
                    accountRoleListRef.loadData({ sysAccountId: sysAccount.id });
                }).catch((message) => {
                    result.success = false;
                    result.message = message;
                }).finally(() => {
                    showResultMessage(result);
                });
            }
        };

    }

    render() {
        return (
            <React.Fragment>
                <UIDataTableView {...this.props}
                    title={'设置用户[' + this.props.location.state.name + ']系统角色'}
                    tableConfigId="sysUserRoleRelateTable"
                    dataUrl="SYSTEM/ACCOUNT/querySysAccountRoleList"
                    selectMode="multi"
                    actionGroupId="sysUserRoleActionGroup"
                    autoLoad={false}
                    actionHandler={this.actionHandler}
                    ref={(inst) => this.accountRoleListRef = inst}
                    onSelectChange={(selectRowKeys) => {
                        this.selectSysAccountRoleIds = selectRowKeys;
                    }}
                    setToolbarState={(topToolBar, selectSysAccountRoleIds) => {
                        if (selectSysAccountRoleIds.length > 0) {
                            topToolBar.enable('remove');
                        } else {
                            topToolBar.disable('remove');
                        }
                    }}
                    onLoadData={(component) => {
                        const sysAccount = component.props.location.state;
                        this.sysAccount = sysAccount;
                        component.loadData({ sysAccountId: sysAccount.id });
                    }}
                />
                <ChooseSysRoleListModalPanel
                    ref={(inst) => this.chooseSysRoleListModalRef = (inst != null ? inst.chooseSysRoleListRef : null)}
                    onSelectSysRole={roleIds => this.selectSysRoleIds = roleIds}
                    actionHandler={this.chooseRoleActionHandler} />
                <ChooseSysRoleGroupListModalPanel
                    ref={(inst) => this.chooseSysRoleGroupListModalRef = (inst != null ? inst.chooseSysRoleGroupListRef : null)}
                    onSelectSysRole={roleIds => this.selectSysRoleIds = roleIds}
                    actionHandler={this.chooseRoleActionHandler} />
            </React.Fragment>
        );
    }
}

/** 
 * 设置系统帐号密码
*/
class SetSysAccountPasswordPanel extends React.Component {

    actionHandler = (actionEvent) => {
        const { component } = actionEvent;
        return {
            doSave: () => {
                const result = {};
                component.getFormData((formData) => {
                    ajax('SYSTEM/ACCOUNT/changePsw', { sysAccountId: formData.id, newPsw: formData.newPassword }).then((data) => {
                        if (data) {
                            result.success = true;
                            result.message = 'message.saveSuccess';
                        }
                    }).catch((reason) => {
                        result.success = true;
                        result.message = reason;
                    }).finally(() => {
                        showResultMessage(result);
                    });
                });
            }
        };
    }

    render() {
        return (
            <Card title={'设置用户[' + this.props.location.state.name + ']登录密码'}>
                <UIForm {...this.props} formConfigId="setUserPasswordForm" actionGroupId="formAddNewEditorActionGroup" actionHandler={this.actionHandler} />
            </Card>
        );
    }
}

/**路由设置 */
const pageContentMap = {
    '/': {
        text: getLocalMessage('sysAccountListPanel.listTitle'),
        icon: '',
        getComponent: (owner, props) => {
            return (<SysAccountListPanel {...props} key="sysAccountList" />);
        }
    },
    '/edit': {
        text: getLocalMessage('sysAccountListPanel.editTitle'),
        icon: 'edit',
        getComponent: (owner, props) => {
            return (<EditSysAccountPanel {...props} key="addNewSysAccount" />);
        }
    },
    '/addNew': {
        text: getLocalMessage('sysAccountListPanel.addNewTitle'),
        icon: 'plus',
        getComponent: (owner, props) => {
            return (<AddNewSysAccountPanel {...props} key="addNewSysAccount" />);
        }
    },
    '/configAccountRoles': {
        text: getLocalMessage('sysAccountListPanel.setAccountRole'),
        icon: 'users',
        getComponent: (owner, props) => {
            return (
                <ConfigSysAccountRolesPanel {...props} key="sysAccountRoleList" />
            );
        }
    },
    '/setSysAccountPassword': {
        text: '设置帐号密码',
        icon: 'key',
        getComponent: (owner, props) => {
            return (
                <SetSysAccountPasswordPanel {...props} key="setSysActionPassword" />
            );
        }
    },
};

/** 
 * 系统帐号管理应用入口
*/
export default class SysAccountListApp extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
        };
    }

    render() {

        return (
            <PageContent pageInstance={this} contentMap={pageContentMap} {...this.props}>

            </PageContent>
        );
    }
};